<template>
    <Dialog ref="dialogRef" :title="title" @confirm="submit" width="500">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="设备类型名称" prop="typeName">
                <el-input v-model="form.typeName" :maxlength="8" placeholder="请输入设备类型名称" />
            </el-form-item>
            <el-form-item label="设备类型图片" prop="files">
                <el-upload ref="uploadRef" :on-exceed="handleExceed" class="avatar-uploader" :on-remove="handleRemove" :on-preview="handlePreview" list-type="picture-card" v-model:file-list="form.files" :limit="1" :on-change="handleFileChange" :show-file-list="true" accept=".svg" action="#" :on-success="handleFileSuccess" :auto-upload="false">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
        </el-form>
        <el-image-viewer v-if="dialogVisible" w-full :url-list="[form.files[0].url]" @close="dialogVisible = false" />
    </Dialog>
</template>
<script setup>
import { getEquipmentTypeById, addEquipmentType, updateEquipmentType, updateImg } from "@/api/simulation/equipmentType.js";
import { ref, getCurrentInstance, watch } from "vue";
import { genFileId } from 'element-plus'
const { proxy } = getCurrentInstance();
const emits = defineEmits(["confirm"]);
defineExpose({ open });
const dialogRef = ref(null);
const form = ref(null);
const formRef = ref(null);
const uploadRef = ref(null);
const title = ref("设备类型");
const dialogVisible = ref(false)
const rules = ref({
    typeName: [{ required: true, message: '设备类型名称不能为空', trigger: 'blur' }],
    files: [{ required: true, message: '设备类型图片不能为空', trigger: 'change' }],
})




/**
 * 打开弹框
 */
async function open(params) {
    reset();
    // 打开弹框
    await dialogRef.value.open();
    if (params) {
        title.value = "编辑";
        getData(params.id);
    } else {
        title.value = "新增";
    }
}

function handlePreview(uploadFile) {
    dialogVisible.value = true
}

function handleExceed(files) {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
}

function handleRemove(file) {
    form.value.imgVos = [];
    form.value.files = [];
}

/**
 * 文件更改 上传
 * @param file 
 * @param fileList 
 */
function handleFileChange(file, fileList) {
    const formData = new FormData();
    formData.append('equipmentTypeImgFile', file.raw);
    updateImg(formData).then(res => {
        if (res.code == 200) {
            form.value.imgVos = [{
                name: res.data.fileName,
                url: res.data.url
            }]
        }
    })

}

/**
 * 获取数据
 * @param id 
 */
async function getData(id) {
    try {
        dialogRef.value.showLoading();
        const res = await getEquipmentTypeById({ id: id });
        form.value = res.data;
        if (form.value.imgVos.length) {
            form.value['files'] = [{ name: form.value.imgVos[0].name, url: import.meta.env.VITE_APP_BASE_API + form.value.imgVos[0].url }]
        }
    } catch (e) {
        console.error(e);
    } finally {
        dialogRef.value.hideLoading();
    }
}



// 表单重置
function reset() {
    form.value = {
        typeName: null,
        remark: null,
        imgVos: []
    }
}


/**
 * 确定
 */
function submit() {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                dialogRef.value.showLoading();
                if (form.value.id) {
                    await updateEquipmentType(form.value);
                } else {
                    await addEquipmentType(form.value);
                }
                proxy.$modal.msgSuccess("操作成功");
                emits("refresh");
                dialogRef.value.close();
            } catch (e) {
                console.error(e);
            } finally {
                dialogRef.value.hideLoading();
            }
        }
    });
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

  
  